const db = require("../models");
const DAO = require("../dao/DAO");
const Notices = db.models.notices;
const Users = db.models.users;





/** 所有list */
exports.findAll = async (req, res) => {
    if (!req.params.type) return res.sendResult({ data: '', code: -1, message: "参数错误！" });
    let pm = {
        page_size: req.body?.page_size ?? 10,
        current_page: req.body?.current_page || 1,
        params: {
            title: req.body?.title ? { [db.Op.substring]: req.body?.title ?? '' } : '',
            type: req.params.type,
            read: req.body?.read ?? null,
            to_user: req.user.id 
        },
        include: [{ model: db.models.users, as: 'fromUser', attributes: ["user_name", "nick_name","avatar"] }],

    }
    DAO.list(Notices, pm, list => {
        res.sendResult(list)
    })
};
/** 未读-分类 */
exports.unread = async (req, res) => {
    try {
        const list = await Notices.findAll({
            include: [
                { model: Users, as: 'fromUser', attributes: ['id', 'user_name', "avatar"] },
                { model: Users, as: 'toUser', attributes: ['id', 'user_name'] }
            ],
            where: { read: 0, to_user: req.user.id },
            attributes: { exclude: ['from_user', 'to_user', 'deletedAt', 'spare1', 'spare2'] },
            order: [
                // ['type', 'ASC'],
                ['createdAt', 'DESC']
            ]
        });
        const data = list.reduce((pre, cur) => {
            const key = cur.type
            if (!pre[key]) {
                pre[key] = []
            }
            pre[key].push(cur)
            return pre
        }, {})
        res.sendResult({ data, code: 0, message: "查询成功！" })
    } catch (error) {
        console.error('查询通知消息出错:', error);
        res.sendResult({ data: '', code: -1, message: "查询失败！" });
    }
};


/** 删除 */
exports.delete = (req, res) => {
    const pm = req.body;
    const to_user = req.user.id;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" });
    DAO.delete(Notices, { id: pm.id, to_user }, data => {
        res.sendResult(data)
    })
};

/** 已读 */
exports.read = (req, res) => {
    const to_user = req.user.id;
    if (!req.params.id) return res.sendResult({ data: '', code: 0, message: "操作成功！" });
    Notices.update({ read: 1 }, { where: { id: req.params.id.split(','), to_user } }).then(data => {
        res.sendResult({ data: '', code: 0, message: "操作成功！" });
    })
};
